﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Win32;
using System.IO;
using System.Text;
using System.Text.Json.Nodes;
using System.Text.Json;
using System.Windows;
using XYAC.Framework.MonitorTireMaterialManual.DataExporter;
using XYAC.Framework.MonitorTireMaterialManual.Entities;
using XYAC.Framework.MonitorTireMaterialManual.Extensions;
using XYAC.Framework.MonitorTireMaterialManual.IServices;
using XYAC.Framework.MonitorTireMaterialManual.LocalData.Models;

namespace XYAC.Framework.MonitorTireMaterialManual.ViewModels
{
    /// <summary>
    /// 班前检点
    /// </summary>
    public partial class PreCheckViewModel : ViewModelBase
    {
        /// <summary>
        /// 临时数据交换目录。
        /// 保存用户选择的最近一次的数据目录。
        /// 重启软件会丢失此目录而采用固定的初始目录。
        /// </summary>
        static string tempDataSwapFolder = "";
        /// <summary>
        /// 主观判断 是 不是
        /// </summary>
        private List<Item> mindCheck;
        public List<Item> MindCheckList
        {
            get => mindCheck;
            set => SetProperty(ref mindCheck, value);
        }

        /// <summary>
        /// 主观判断 合格 还是不合格
        /// </summary>
        private List<Item> mindPassList;
        public List<Item> MindPassList
        {
            get => mindPassList;
            set => SetProperty(ref mindPassList, value);
        }

        /// <summary>
        /// 班次清单
        /// </summary>
        private List<Item> shiftList;
        public List<Item> ShiftList
        {
            get => shiftList;
            set => SetProperty(ref shiftList, value);
        }

        public static string TempDataSwapFolder
        {
            get => tempDataSwapFolder;
            set => tempDataSwapFolder = value;
        }

        public IOptionsMonitor<AppConfig> AppConfig { get; }

        private IServiceProvider provider;
        [ObservableProperty]
        private string _scanDatetime;
        public ILogger Logger { get; }
        [ObservableProperty]
        private PreCheckReport _preCheckReport;
        [ObservableProperty]
        private bool _isReadonly=false;
        
        public DataFile DataFile { get; private set; }
        public Action CloseWindow { get; internal set; }

        public PreCheckViewModel(IOptionsMonitor<AppConfig> appConfig, ILogger<SemiSteelTriangleRubberViewModel> logger, IServiceProvider provider)
        {
            AppConfig = appConfig;
            this.provider = provider;
            this.Logger = logger;
            this.UserId = this.AppConfig.CurrentValue.UserId;
            //看用户怎么选，是本地优先（即用户选定优先） 还是中间表优先
            //this.CurrentShift = this.AppConfig.CurrentValue.CurrentShift;
            this.CurrentShift = AppConfig.CurrentValue.GetCurrentShift();
            ScanDatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            MindCheckList = new List<Item>();
            MindCheckList.Add(new Item("√", "True"));
            MindCheckList.Add(new Item("×", "False"));

            MindPassList = new List<Item>();
            MindPassList.Add(new Item("合格", "True"));
            MindPassList.Add(new Item("不合格", "False"));

            ShiftList = new List<Item>();
            ShiftList.Add(new Item("早班", "早"));
            ShiftList.Add(new Item("夜班", "夜"));
            isPrecheck();
        }

        public void initData()
        {
            gainPrecheckData();
        }

        /// <summary>
        /// 打开txt报表数据
        /// </summary>
        [RelayCommand]
        private void OpenReportData()
        {
            try
            {
                if (isPrecheck())
                {
                    MessageBox.Show("本班次今日已做过班前检点！", "应用提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                string tempDir = TempDataSwapFolder;
                if (string.IsNullOrEmpty(tempDir))
                    tempDir = this.AppConfig.CurrentValue.Folder3Path;
                // 创建并配置 OpenFileDialog 对象
                var openFileDialog = new OpenFileDialog
                {
                    InitialDirectory = tempDir,
                    Title = "Open Text File",
                    Filter = "文本文件 (*.txt)|*.txt",
                    Multiselect = false
                };

                // 显示文件选择对话框
                if (openFileDialog.ShowDialog() == true)
                {
                    string fileName = openFileDialog.FileName;
                    FileInfo fileInfo = new FileInfo(fileName);
                    TempDataSwapFolder = fileInfo.DirectoryName;

                    this.AppConfig.CurrentValue.Folder3Path = TempDataSwapFolder;
                    SaveNewJsonConfig();

                    // 加载并解析数据文件
                    this.DataFile = DataFileParser.LoadFromFile(fileName);
                    List<string> errors = null;
                    if (DataFile.Validate(out errors))
                    {
                        this.DataFile = DataFileParser.LoadFromFile(fileName);
                        if (DataFile.Validate(out errors))
                        {
                            var UploadViewModel = this.provider.GetService<QualityDataUploadViewModel>();

                            //验证成功,赋值给本地视图模型
                            this.PreCheckReport = new()
                            {
                                SerialNumber = "0000000",//UploadViewModel.CurrentUserChoicePlan?.InspectModel.SERIAL_NUMBER,
                                ScanedDatetime = ScanDatetime,
                                PlanId = "0000000",//UploadViewModel.CurrentUserChoicePlan?.InspectModel.SERIAL_NUMBER,
                                Shift = CurrentShift, //UploadViewModel.CurrentUserChoicePlan?.InspectModel.SHIFT,
                                SpecNameInfact = "0000000",// UploadViewModel.CurrentUserChoicePlan?.InspectModel.PART_NUMBER,
                                SpecName = this.DataFile.TypeName,
                                Data7 = _data7(),
                                Data8 = _data8(),
                                Data9 = _data9(),
                                Data10 = _data10(),
                                Data11 = _data11(),
                                Data12 = _data12(),
                                Data13 = _data13(),
                                Data14 = _data14(),
                                Data15 = _data15(),
                                Data16 = _data16(),
                                Data17 = _data17(),
                                Data18 = _data18(),
                                Data19 = _data19(),
                                Data20 = _data20(),
                                Data21 = _data21(),
                                Data22 = _data22(),
                                Data23 = _data23(),
                                Data24 = _data24(),
                                Data25 = _data25(),
                                Data26 = _data26(),
                                Data27 = _data27(),
                                Data28 = _data28(),
                                Data29 = _data29(),
                                Data30 = _data30(),
                                Data31 = _data31(),
                                Data32 = _data32(),
                                Data33 = _data33(),
                                Data34 = _data34(),
                                Eqp = "000000",
                                Remark = "",
                                ReportTime = DateTime.Now,
                                PlanDate = DateTime.Now,
                                DataFileJson = JsonSerializeHelper.SerializeObjectToJson(DataFile),
                            };
                        }
                        else
                        {
                            //弹出exception
                        }
                    }
                    else
                    {
                        // 弹出错误信息
                        MessageBox.Show("文件验证失败:\n" + string.Join("\n", errors), "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                // 记录错误日志
                Logger?.LogError(ex.Message, ex);
                MessageBox.Show("打开文件时出现错误: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 上传当前条码以及关联数据到远程数据库,同时记录到本地数据库
        /// </summary>
        [RelayCommand]
        private void UploadCurrentData()
        {
            if (this.PreCheckReport is null)
            {
                MessageBox.Show("请先选择扫描的数据文件！");
                return;
            }

            if (string.IsNullOrEmpty(this.UserId) || this.UserId.Trim().Length > 8)
            {
                MessageBox.Show("检测员ID不合法");
                return;
            }

            this.PreCheckReport.UserId = this.UserId;
            this.PreCheckReport.Shift = this.CurrentShift;

            //this.SemiSteelTriangleRubberReport.CrossSectionShape = this.CrossSectionShape;
            //this.SemiSteelTriangleRubberReport.PassStatus = this.PassStatus;
            //this.SemiSteelTriangleRubberReport.SpecNameInfact = this.CurentInspect.PART_NUMBER;

            //此处用于同步到本地库
            //此处代码逻辑
            //插入本地库
            //更新中间表状态

            var msg = "确实要上报数据！";//  GetFormattedPropertyComments(this.SemiSteelTriangleRubberReport);
            if (MessageBox.Show(msg, "上报数据", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                using (var scope = this.provider.CreateScope())
                {
                    var reportService = scope.ServiceProvider.GetService<ILocalReportService>();
                    //var uploadViewModel = scope.ServiceProvider.GetService<QualityDataUploadViewModel>();
                    var dt = AppConfig.CurrentValue.GetCurrentProcuceDate();
                    var tempInspect = new YB_LOT_INSPECT_Local
                    {
                        CREATION_DATE = DateTime.Now,
                        EQP = "00000000",
                        SERIAL_NUMBER = "00000000",
                        PLANID = "00000000",
                        PLAN_DATE = dt,
                        LJ_ID = 0,

                        PART_NUMBER = "标准块",
                        SHIFT = this.CurrentShift,
                        RECEIVE_FLAG = "PENDING",
                        RemoteSyncDate = DateTime.Now,
                        RemoteSyncState = false,
                        LocalSyncState = 0,
                    };

                    //int ret = reportService.Add<PreCheckReport>(this.PreCheckReport, uploadViewModel.CurrentUserChoicePlan.InspectModel);

                    int ret = reportService.Add<PreCheckReport>(this.PreCheckReport, tempInspect);

                    if (ret == 0)
                    {
                        MessageBox.Show("保存数据失败,请稍后重试");
                    }
                    else
                    {
                        //关闭窗体
                        this.CloseWindow?.Invoke();
                    }
                }
            }
        }

        /// <summary>
        /// 检查是否已做过班前检点。
        /// </summary>
        /// <returns>已做过，返回真</returns>
        private bool isPrecheck2()
        {
            //using var scope = this.provider.CreateScope();
            //var reportService = scope.ServiceProvider.GetService<ILocalReportService>();

            var reportService = provider.GetService<ILocalReportService>();
            var CurrentShift = AppConfig.CurrentValue.GetCurrentShift();
            return reportService.isCheck(CurrentShift, DateTime.Now);
        }
        public bool isPrecheck()
        {
            using var scope = this.provider.CreateScope();
            var reportService = scope.ServiceProvider.GetService<ILocalReportService>();
            var CurrentShift = AppConfig.CurrentValue.GetCurrentShift();
            var dt = AppConfig.CurrentValue.GetCurrentProcuceDate();
            return reportService.isCheck(CurrentShift, dt);
        }

        private void gainPrecheckData()
        {
            var reportService = provider.GetService<ILocalReportService>();
            var CurrentShift = AppConfig.CurrentValue.GetCurrentShift();
            var dt = AppConfig.CurrentValue.GetCurrentProcuceDate();
            var rs = reportService.findCheckData(CurrentShift, dt);//DateTime.Now
            if (rs != null)
            {
                PreCheckReport = (PreCheckReport)rs;
                this.IsReadonly = true;
            }
            else
                this.IsReadonly = false;
        }

        public string GetFormattedPropertyComments<T>(T value)
        {
            // 获取 T 类型的所有属性
            var type = typeof(T);
            var properties = type.GetProperties();

            // 用于存储格式化的文本
            StringBuilder formattedText = new StringBuilder();

            foreach (var property in properties)
            {
                // 获取属性上的所有注释（Description）
                var summaryAttribute = property.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false)
                                                .Cast<System.ComponentModel.DescriptionAttribute>()
                                                .FirstOrDefault();

                // 获取属性的值
                var propertyValue = property.GetValue(value);

                if (summaryAttribute != null)
                {
                    if (propertyValue != null && float.TryParse(propertyValue.ToString(), out float fValue))
                    {
                        // 如果存在注释（Description），将其格式化到文本中，显示注释和值
                        formattedText.AppendLine($"{summaryAttribute.Description}: {fValue.ToString("F2")}");
                    }
                    else
                    {
                        // 如果存在注释（Description），将其格式化到文本中，显示注释和值
                        formattedText.AppendLine($"{summaryAttribute.Description}: {propertyValue}");
                    }
                }
            }

            // 返回格式化后的文本
            return formattedText.ToString();
        }
        internal void UpdateUserId(string text)
        {
            try
            {
                this.AppConfig.CurrentValue.UserId = text;
                SaveNewJsonConfig();
            }
            catch (Exception ex)
            {
                Logger?.LogError("保存用户ID失败", ex);
            }
        }

        internal void UpdateCurrentShift(string text)
        {
            try
            {
                this.AppConfig.CurrentValue.CurrentShift = text;
                SaveNewJsonConfig();
            }
            catch (Exception ex)
            {
                Logger?.LogError("保存当前班次失败！", ex);
            }
        }

        private void SaveNewJsonConfig()
        {
            try
            {
                const string configPath = "./Configs/";
                const string configFileName = "AppConfig.json";
                const string tempFileName = "AppConfig_temp.json";

                string configFullPath = Path.Combine(configPath, configFileName);
                string tempFullPath = Path.Combine(configPath, tempFileName);

                // 复制原始配置文件到临时文件
                File.Copy(configFullPath, tempFullPath, overwrite: true);
                var currentValue = this.AppConfig.CurrentValue.Clone();
                // 修改临时文件
                JsonObject appSetting;
                using (FileStream fs = new FileStream(tempFullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                {
                    appSetting = JsonNode.Parse(fs).AsObject();

                    // 将当前的 CurrentAppConfig 序列化为 JsonNode
                    JsonNode sourceJsonNode = JsonSerializer.SerializeToNode(currentValue);

                    // 替换 "AppConfig" 节点
                    appSetting["AppConfig"] = sourceJsonNode;

                    // 清空文件并重置位置
                    fs.SetLength(0);
                    fs.Position = 0;

                    var options = new JsonSerializerOptions
                    {
                        WriteIndented = true // 格式化输出
                    };
                    JsonSerializer.Serialize(fs, appSetting, options);
                }

                // 原子性地替换原始配置文件
                File.Replace(tempFullPath, configFullPath, null);
            }
            catch (Exception ex)
            {
                this.Logger.LogError("保存配置文件失败", ex);
            }
        }

        [ObservableProperty]
        private string _userId;

        [ObservableProperty]
        private string _specNameInfact;
        [ObservableProperty]
        private string _eqp;
        [ObservableProperty]
        private string _scanedDatetime;
        [ObservableProperty]
        private string _serialNumber;

        /// <summary>
        /// 当前班次
        /// </summary>
        [ObservableProperty]
        private string _currentShift;
        /// <summary>
        /// 第一关键点厚度 标准
        /// TXT文档，[Keys]下面第一行的右边数字
        /// </summary>

        public double? _data7()
        {
            return DataFile.StableKeys[0].Value;
        }
        /// <summary>
        /// 第一关键点厚度 实测
        /// TXT文档，[MeasureKeys]下面第一行的右边数字
        /// </summary>
        public double? _data21()
        {
            return DataFile.MeasureKeys[0].Value;
        }
        /// <summary>
        /// 第二关键点厚度 标准
        /// TXT文档，[Keys]下面第二行的右边数字
        /// </summary>
        public double? _data8()
        {
            return DataFile.StableKeys[1].Value;
        }
        /// <summary>
        /// 第二关键点厚度 实测
        /// TXT文档，[MeasureKeys]下面第二行的右边数字
        /// </summary>
        public double? _data22()
        {
            return DataFile.MeasureKeys[1].Value;
        }
        /// <summary>
        /// 第三关键点厚度 标准
        /// TXT文档，[Keys]下面第三行的右边数字
        /// </summary>
        public double? _data9()
        {
            return DataFile.StableKeys[2].Value;
        }
        /// <summary>
        /// 第三关键点厚度 实测
        /// TXT文档，[MeasureKeys]下面第三行的右边数字
        /// </summary>
        public double? _data23()
        {
            return DataFile.MeasureKeys[2].Value;
        }

        /// <summary>
        /// 第四关键点厚度 标准
        /// TXT文档，[Keys]下面第四行的右边数字
        /// </summary>
        public double? _data10()
        {
            return DataFile.StableKeys[3].Value;
        }
        /// <summary>
        /// 第四关键点厚度 实测
        /// TXT文档，[MeasureKeys]下面第四行的右边数字
        /// </summary>
        public double? _data24()
        {
            return DataFile.MeasureKeys[3].Value;
        }
        /// <summary>
        /// 第五关键点厚度 标准
        /// TXT文档，[Keys]下面第五行的右边数字
        /// </summary>
        public double? _data11()
        {
            return DataFile.StableKeys[4].Value;
        }
        /// <summary>
        /// 第五关键点厚度 实测
        /// TXT文档，[MeasureKeys]下面第五行的右边数字
        /// </summary>
        public double? _data25()
        {
            return DataFile.MeasureKeys[4].Value;
        }

        /// <summary>
        /// 第六关键点厚度 标准
        /// TXT文档，[Keys]下面第六行的右边数字
        /// </summary>
        public double? _data12()
        {
            return DataFile.StableKeys[5].Value;
        }
        /// <summary>
        /// 第六关键点厚度 实测
        /// TXT文档，[MeasureKeys]下面第六行的右边数字
        /// </summary>
        public double? _data26()
        {
            return DataFile.MeasureKeys[5].Value;
        }

        /// <summary>
        /// 第七关键点厚度 标准
        /// TXT文档，[Keys]下面第七行的右边数字
        /// </summary>
        public double? _data13()
        {
            return DataFile.StableKeys[6].Value;
        }
        /// <summary>
        /// 第七关键点厚度 实测
        /// TXT文档，[MeasureKeys]下面第七行的右边数字
        /// </summary>
        public double? _data27()
        {
            return DataFile.MeasureKeys[6].Value;
        }

        /// <summary>
        /// 第一关键点宽度 标准
        /// TXT文档，[Keys]下面第一行的左边数字
        /// </summary>
        public double? _data14()
        {
            return DataFile.StableKeys[0].Coordinate;
        }
        /// <summary>
        /// 第一关键点宽度 实测
        /// TXT文档，[MeasureKeys]下面第一行的左边数字
        /// </summary>
        public double? _data28()
        {
            return DataFile.MeasureKeys[0].Coordinate;
        }

        /// <summary>
        /// 第二关键点宽度 标准
        /// TXT文档，[Keys]下面第二行的左边数字
        /// </summary>
        public double? _data15()
        {
            return DataFile.StableKeys[1].Coordinate;
        }
        /// <summary>
        /// 第二关键点宽度 实测
        /// TXT文档，[MeasureKeys]下面第二行的左边数字
        /// </summary>
        public double? _data29()
        {
            return DataFile.MeasureKeys[1].Coordinate;
        }

        /// <summary>
        /// 第三关键点宽度 标准
        /// TXT文档，[Keys]下面第三行的左边数字
        /// </summary>
        public double? _data16()
        {
            return DataFile.StableKeys[2].Coordinate;
        }
        /// <summary>
        /// 第三关键点宽度 实测
        /// TXT文档，[MeasureKeys]下面第三行的左边数字
        /// </summary>
        public double? _data30()
        {
            return DataFile.MeasureKeys[2].Coordinate;
        }
        /// <summary>
        /// 第四关键点宽度 标准
        /// TXT文档，[Keys]下面第四行的左边数字
        /// </summary>
        public double? _data17()
        {
            return DataFile.StableKeys[3].Coordinate;
        }
        /// <summary>
        /// 第四关键点宽度 实测
        /// TXT文档，[MeasureKeys]下面第四行的左边数字
        /// </summary>
        public double? _data31()
        {
            return DataFile.MeasureKeys[3].Coordinate;
        }

        /// <summary>
        /// 第五关键点宽度 标准
        /// TXT文档，[Keys]下面第五行的左边数字
        /// </summary>
        public double? _data18()
        {
            return DataFile.StableKeys[4].Coordinate;
        }
        /// <summary>
        /// 第五关键点宽度 实测
        /// TXT文档，[MeasureKeys]下面第五行的左边数字
        /// </summary>
        public double? _data32()
        {
            return DataFile.MeasureKeys[4].Coordinate;
        }

        /// <summary>
        /// 第六关键点宽度 标准
        /// TXT文档，[Keys]下面第六行的左边数字
        /// </summary>
        public double? _data19()
        {
            return DataFile.StableKeys[5].Coordinate;
        }
        /// <summary>
        /// 第六关键点宽度 实测
        /// TXT文档，[MeasureKeys]下面第六行的左边数字
        /// </summary>
        public double? _data33()
        {
            return DataFile.MeasureKeys[5].Coordinate;
        }

        /// <summary>
        /// 第七关键点宽度 标准
        /// TXT文档，[Keys]下面第七行的左边数字
        /// </summary>
        public double? _data20()
        {
            return DataFile.StableKeys[6].Coordinate;
        }
        /// <summary>
        /// 第七关键点宽度 实测
        /// TXT文档，[MeasureKeys]下面第七行的左边数字
        /// </summary>
        public double? _data34()
        {
            return DataFile.MeasureKeys[6].Coordinate;
        }
    }
}
